package com.zjpavt.taiyuan.utils;

import com.alibaba.dubbo.common.utils.StringUtils;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @Auther: zhuliangyu
 * @Date: 2019/3/29 21:03
 * @Description:
 */
public class HttpClientUtil {
	private static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
	private static HttpClient client;

	static {
		MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
		HttpConnectionManagerParams params = connectionManager.getParams();
		//设置连接成功超时时间2s
		params.setConnectionTimeout(2000);
		//设置获取数据超时时间10s
		params.setSoTimeout(10000);
		//检测每次连接是否可用，可能会耽误20ms左右
		params.setStaleCheckingEnabled(true);
		//设置同一个域名最大支持连接数
		params.setDefaultMaxConnectionsPerHost(1000);
		//设置最大连接数
		params.setMaxTotalConnections(1000);
		client = new HttpClient(connectionManager);
	}

	/**
	 * post请求
	 *
	 * @param post          post
	 * @param requestParams json格式的请求体数据
	 * @return 响应的数据(json)
	 */
	public static String post(PostMethod post, String requestParams, String cookie) throws Exception {
		String data = "";
		post.addRequestHeader("Content-type", "application/json; charset=utf-8");
		if (StringUtils.isNotEmpty(cookie)) {
			post.setRequestHeader("Cookie", cookie);
		}
		try {
			if (StringUtils.isNotEmpty(requestParams)) {
				RequestEntity se = new StringRequestEntity(requestParams, "application/json", "UTF-8");
				post.setRequestEntity(se);
			}
			int statusCode = client.executeMethod(post);
			if (statusCode != HttpStatus.SC_OK) {
				logger.error("请求失败: "
						+ post.getStatusLine());
				return null;
			}
			return readResponseData(post.getResponseBodyAsStream());
		} finally {
			post.releaseConnection();
		}
	}

	/**
	 * get请求
	 *
	 * @param get get
	 * @return 响应的数据(json)
	 */
	public static String get(GetMethod get, String cookie)throws Exception {
		String data = "";
		get.addRequestHeader("Content-type", "application/json; charset=utf-8");
		if (StringUtils.isNotEmpty(cookie)) {
			get.setRequestHeader("Cookie", cookie);
		}
		try {
			int statusCode = client.executeMethod(get);
			if (statusCode != HttpStatus.SC_OK) {
				logger.error("请求失败: "
						+ get.getStatusLine());
				return null;
			}
			return readResponseData(get.getResponseBodyAsStream());
		} finally {
			get.releaseConnection();
		}
	}

	/**
	 * 通过getResponseBodyAsStream()获取响应数据
	 * @param inputStream
	 * @return
	 * @throws IOException
	 */
	private static String readResponseData(InputStream inputStream) throws IOException {
		//获取字符流时，需指定编码格式，否则在转换为String时会导致中文乱码问题
		try(InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"UTF-8");
		    BufferedReader reader = new BufferedReader(inputStreamReader)){
			StringBuilder stringBuilder = new StringBuilder();
			String temp;
			while ((temp = reader.readLine()) != null) {
				stringBuilder.append(temp);
				stringBuilder.append("\r\n");
			}
			return stringBuilder.toString();
		}
	}
}
